#include <FreeImage/FreeImage.h>
#include <iostream>
#include <RevEng/RevEng.hpp>
#include "IGraphics.hpp"

using namespace RevEng;
using namespace RevEng::Math;
using namespace Graphics;

IVertexBuffer *Verts;

ITexture* LoadTexture(char* tex)
{
	ITexture* TexOut = NULL;
	Size3ui TexSize(1, 1, 1);
	FIBITMAP *pBitmap = NULL;
	FREE_IMAGE_FORMAT eFormat = FIF_UNKNOWN;
	UInt8* pTexData;
	UInt8* pImgData;

	if (tex == NULL)
		return NULL;

	eFormat = FreeImage_GetFileType(tex);
	pBitmap = FreeImage_Load(eFormat, tex);

	if (pBitmap == NULL)
		return NULL;
	
	TexOut = dynamic_cast<ITexture*>(IObject::New( GR_TEXTURE ));

	TexSize.SetWidth( FreeImage_GetWidth(pBitmap) );
	TexSize.SetHeight( FreeImage_GetHeight(pBitmap) );

	TexOut->SetSize( TexSize );

	pImgData = FreeImage_GetBits(pBitmap);
	pTexData = (UInt8*)TexOut->Lock();

	memcpy(pTexData, pImgData, 3*TexSize.GetVolume());
	TexOut->Unlock();

	return TexOut;
}


int main()
{
	bool bExe= true;
	Material MyMaterial;
	IGraphics::Instance();

	MyMaterial.Ambient = Vector4s(1.0f, 1.0f, 1.0f, 1.0f);
	MyMaterial.Diffuse = Vector4s(1.0f, 1.0f, 1.0f, 1.0f);
	MyMaterial.Emissive = Vector4s(0.5f, 0.5f, 0.5f, 1.0f);
	MyMaterial.Texture = LoadTexture( "../media/pasto02.jpg" );
	MyMaterial.Texture->AddRef();

	Verts = dynamic_cast<IVertexBuffer*>(IObject::New(GR_VERTEX_BUFFER));
	Verts->AddRef();

	//Generar los vertices
	Verts->SetVertexCount(4);
	Vertex* pVertices = static_cast<Vertex*>(Verts->Lock());

	pVertices[0].Coord = Vector3s(-0.5f, 0.5f, 0.0f);
	pVertices[0].Normal = Vector3s(0.0f, 0.0f, 0.0f);
	pVertices[0].TexCoord = Vector2s(0.0f, 1.0f);

	pVertices[1].Coord = Vector3s(0.5f, 0.5f, 0.0f);
	pVertices[1].Normal = Vector3s(0.0f, 0.0f, 0.0f);
	pVertices[1].TexCoord = Vector2s(1.0f, 1.0f);

	pVertices[2].Coord = Vector3s(-0.5f, -0.5f, 0.0f);
	pVertices[2].Normal = Vector3s(0.0f, 0.0f, 0.0f);
	pVertices[2].TexCoord = Vector2s(0.0f, 0.0f);

	pVertices[3].Coord = Vector3s(0.5f, -0.5f, 0.0f);
	pVertices[3].Normal = Vector3s(0.0f, 0.0f, 0.0f);
	pVertices[3].TexCoord = Vector2s(1.0f, 0.0f);

	Verts->Unlock();

	while(bExe)
	{
		bExe = IGraphics::Instance()->DoEvents();

		IGraphics::Instance()->BeginFrame( Vector4s(0.0f, 0.0f, 0.0f, 1.0f) );

		IGraphics::Instance()->SetMaterial(MyMaterial);
		IGraphics::Instance()->SetVertices(Verts);
		IGraphics::Instance()->Render(RE_TRIANGLE_STRIP);

		IGraphics::Instance()->EndFrame();
	}

	MyMaterial.Texture->Release();
	Verts->Release();
	IGraphics::Delete();

	return 0;
}
